<template>
    <div ref="popconfirmRef" class="pe-popconfirm" @click.stop="onClick">
        <slot></slot>
        <Popup v-model="show" ref="popupRef" :domFlag="false">
            <div class="pe-popconfirm-box">
                <div class="pe-popconfirm-header">
                    <icon v-if="!hideIcon" :style="{ color: iconColor }" />
                    <div class="pe-popconfirm-title">{{ title }}</div>
                </div>
                <div class="pe-popconfirm-button">
                    <Button size="small" :type="cancelButtonType" @click="onConfirm">{{ cancelButtonText }}</Button>
                    <Button size="small" :type="confirmButtonType" @click="onCancel">{{ confirmButtonText }}</Button>
                </div>
            </div>
        </Popup>
    </div>
</template>

<script setup lang="ts">
import { Component, nextTick, ref, watch } from "vue"
import Popup from "../popup/popup.vue";
import Info from "../../icons/info.vue";
import Button from "../button/button.vue";

/**
 * @param title 标题
 * @param confirm-button-text 确认按钮文字
 * @param cancel-button-text 取消按钮文字
 * @param confirm-button-type 确认按钮类型
 * @param cancel-button-type 取消按钮类型
 * @param icon 自定义图标
 * @param icon-color Icon 颜色
 * @param hide-icon 是否隐藏 Icon
 */
interface Props {
    title?: string,
    confirmButtonText?: string,
    cancelButtonText?: string,
    confirmButtonType?: 'primary' | 'success' | 'warning' | 'error' | 'info' | '',
    cancelButtonType?: 'primary' | 'success' | 'warning' | 'error' | 'info' | '',
    icon?: string | Component,
    iconColor?: string,
    hideIcon?: boolean
}

const props = withDefaults(defineProps<Props>(), {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    confirmButtonType: "primary",
    cancelButtonType: "",
    icon: Info,
    iconColor: "#f90",
    hideIcon: false
})

const emits = defineEmits(["confirm", "cancel"])

const show = ref<boolean>(false)

const popconfirmRef = ref<HTMLDivElement>()
const popupRef = ref<any>()

watch(props, () => {
    nextTick(() => {
        popupRef.value?.setRef(popconfirmRef.value)
    })
}, { immediate: true })

const onClick = () => {
    nextTick(() => {
        show.value = true
    })
}

const onConfirm = () => {
    emits("confirm")
    show.value = false
}

const onCancel = () => {
    emits("cancel")
    show.value = false
}
</script>

<script lang="ts">
export default {
    name: "pe-popconfirm"
}
</script>